﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;

namespace FieldUpdater.Classes
{
    public class ListDAL
    {
        #region Constants
        private const string PropertyName = "FieldAssociationDefinitions";
        #endregion

        #region Properties
        public Guid ListID { get; set; }

        private SPList m_List = null;
        public SPList List
        {
            get
            {
                if (m_List == null)
                    m_List = SPContext.Current.Web.Lists[this.ListID];
                return m_List;
            }
        } 
        #endregion

        #region Constructors
        public ListDAL(Guid listID)
        {
            this.ListID = listID;
        }
        #endregion

        #region Methods
        public FieldAssociationCollection GetDefinitions()
        {
            var list = this.List;
            if (list.RootFolder.Properties.ContainsKey(ListDAL.PropertyName))
                return FieldAssociationCollection.FromString(
                    (string)list.RootFolder.Properties[ListDAL.PropertyName]);

            return new FieldAssociationCollection();
        }

        public void SaveDefinitions(FieldAssociationCollection definitions)
        {
            string definitionsXml = definitions.ToString();

            var list = this.List;
            var rootFolder = list.RootFolder;
            rootFolder.Properties[ListDAL.PropertyName] = definitionsXml;
            rootFolder.Update();
        }
        #endregion
    }
}